package com.itheima.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.Dto.OrderDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.Dto.OrderDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Orders;
import com.itheima.common.PageParm;
import com.itheima.common.PageParm;
import com.itheima.common.OrderPageParam;
import com.itheima.common.PageParm;
import com.itheima.common.R;
import com.itheima.service.OrderService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 订单管理
 */
@RestController
@RequestMapping("/order")
@Slf4j
@Transactional
public class OrderController {


    @Autowired
    private OrderService orderService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 提交订单，即添加订单表及订单详细表
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders,HttpSession session){
        int row = orderService.insert(orders, session);
        if(row>0) {

            shoppingCartService.delete();

            return R.success("添加订单成功");
        }
        else return R.error("添加订单失败");
    }



    @GetMapping("/page")
    public R<IPage<Orders>> look(OrderPageParam pageParm){
        System.out.println("pageParm = " + pageParm);
        try {
            IPage<Orders> ordersIPage = orderService.look(pageParm);
            return R.success(ordersIPage);
        }catch (Exception e) {
            return R.error("查询失败");
        }
    }


    @GetMapping("/userPage")
    public R<IPage<OrderDto>> findByPage(PageParm param) {
        /*
        * 1. 创建分页对象
        * 2. 传入分页参数
        * 3. 获取订单列表
        * 4. 遍历订单, 获取订单id
        * 5. 根据订单 id 获取订单详情
        * 6. 组合成 orderDto
        * 7. 返回
        *
        * */
        try {
            IPage<OrderDto> orders = orderService.findByPage(param);
            return R.success(orders);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败");
        }
    }

}
